package vns.client.helper;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.ListBox;

public class MultiselectListBox extends ListBox {
	private List<ValueAndName> values = new ArrayList<ValueAndName>();
	private static boolean ctrl = false;

	public MultiselectListBox() {
		super(true);
		init();
	}

	public MultiselectListBox(boolean isMultiselec) {
		super(isMultiselec);
		init();
	}

	private void init() {
		this.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				ListBox lb = (ListBox) event.getSource();
				String value = lb.getValue(lb.getSelectedIndex());
				String name = lb.getItemText(lb.getSelectedIndex());
				changeValue(value, name);
			}
		});
		this.addKeyDownHandler(new KeyDownHandler() {

			@Override
			public void onKeyDown(KeyDownEvent event) {
				if (event.isControlKeyDown())
					masked(true);
				else
					masked(false);
			}
		});
		this.addKeyUpHandler(new KeyUpHandler() {

			@Override
			public void onKeyUp(KeyUpEvent event) {
				if (event.isControlKeyDown())
					masked(true);
				else
					masked(false);
			}
		});
	}

	private void changeValue(String value, String name) {
		if (!ctrl) {
			values.clear();
			ValueAndName van = new ValueAndName(value, name);
			values.add(van);
		} else {
			int index = containInList(value);
			if (index == -1) {
				ValueAndName van = new ValueAndName(value, name);
				values.add(van);
			} else
				values.remove(index);
		}
		// test
		Window.alert("Tongso:"+values.size());
		for (ValueAndName van : values) {
			Window.alert(van.getValue() + " | " + van.getName());
		}
	}

	private void masked(boolean isControlKeyDown) {
		ctrl = isControlKeyDown;
		// Window.alert(String.valueOf(ctrl));
	}

	private int containInList(String value) {
		int i = 0;
		for (ValueAndName van : values) {
			if (van.getValue().equalsIgnoreCase(value))
				return i;
			i++;
		}
		return -1;

	}

	public List<ValueAndName> getValues() {
		return values;
	}
}
